package com.meixiang.fragment.momentsContentFragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.lzy.okhttputils.model.HttpParams;
import com.meixiang.R;
import com.meixiang.activity.moments.PostDetailsActivity;
import com.meixiang.adapter.moments.AttentionAdapter;
import com.meixiang.entity.moments.MomentsAttentionBean;
import com.meixiang.entity.moments.MomentsAttentionList;
import com.meixiang.global.Config;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.BaseFragment;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbJsonUtil;
import com.meixiang.util.AbToastUtil;
import com.meixiang.view.swipetoloadlayout.base.OnLoadMoreListener;
import com.meixiang.view.swipetoloadlayout.base.OnRefreshListener;
import com.meixiang.view.swipetoloadlayout.base.SwipeToLoadLayout;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 作者：黑哥 on 2016/5/5 18:10
 * 关注
 */
public class AttentionFragment extends BaseFragment implements OnRefreshListener, OnLoadMoreListener {

    @Bind(R.id.refresh)
    SwipeToLoadLayout mRefresh;
    private FragmentActivity mActivity;
    @Bind(R.id.swipe_target)
    RecyclerView mRecyclerView;

    private  boolean isLikeClick;
    //    //判断当前关注是否点击了
    private  boolean isAttention;
    //当前评论是否点击了
    private  boolean isComment;
    private AttentionAdapter mAdapter;
    private View view;
    private List<MomentsAttentionList> mList=new ArrayList<>();
    private  MomentsAttentionBean bean;
    public AttentionFragment() {

    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.attention_fragment, container, false);
        super.onCreateView(inflater, container, savedInstanceState);
        mActivity = getActivity();
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initTitle() {

    }
    private  int position;
    @Override
    protected void initView() {
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
            linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            mRecyclerView.setLayoutManager(linearLayoutManager);
        mAdapter = new AttentionAdapter(getActivity(), getActivity());
        mRecyclerView.setAdapter(mAdapter);

        mRefresh.setOnRefreshListener(this);
        mRefresh.setOnLoadMoreListener(this);

        /**检查RecyclerView是否滑动底部如果滑到*/
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if (!ViewCompat.canScrollVertically(recyclerView, 1)) {
                        mRefresh.setLoadingMore(true);
                    }
                }
            }
        });

        //Item的点击事件
        mAdapter.setOnItemClickListener(new AttentionAdapter.onItemClickListener() {

            @Override
            public void onLikeItemClick(View v, int position,TextView mTvLike) {
                //未点赞
                if (mAdapter.getData().get(position).getMyLaud().equals("0")){
                    AddLaud(position,mTvLike);
                }else {
                    CancelLaud(position);
                }

            }
            //关注
            @Override
            public void onAttentionItemClick(View v, int position) {
                //未关注
                if (mAdapter.getData().get(position).getMyConcern().equals("0")){
                    AddConcern(position);
                }else {
                    CancelConcern(position);
                }
            }
            @Override
            public void onCheckoutPositionItemClick(View v, int position) {
                Intent intent=new Intent(mActivity, PostDetailsActivity.class);
                intent.putExtra("commentId",mAdapter.getData().get(position).getCommentId());
                startActivity(intent);
            }

            @Override
            public void onMessageItemClick(View v, int position) {
                Intent intent=new Intent(mActivity, PostDetailsActivity.class);
                intent.putExtra("commentId",mAdapter.getData().get(position).getCommentId());
                intent.putExtra("comment","1");
                startActivity(intent);
            }
        });


    }
    @Override
    protected void setData() {
        showLoading();
        getAttentionData(1,true);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser){
            if (mAdapter!=null){
                getAttentionData(1,true);
            }

        }
    }

    //点赞
    private void AddLaud(final int position,final TextView mTvLike) {
        HttpParams params = new HttpParams();
        params.put("commentId", mAdapter.getData().get(position).getCommentId());
        HttpUtils.post(Config.MOMENTS_ADD_LAUD, params, new HttpCallBack(mActivity) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                Tool.showTextToast(activity, message);
                Tool.Like(activity,mTvLike);
                MomentsAttentionList moments = mAdapter.getData().get(position);
                moments.setMyLaud("1");
                moments.setLaudNumber((Integer.parseInt(moments.getLaudNumber()) + 1) + "");
                mAdapter.notifyItemChanged(position);
            }

            @Override
            public void onError(String code, String message) {

            }
        });
    }


    //取消点赞
    private void CancelLaud(final  int position){
        HttpParams params = new HttpParams();
        params.put("commentId",  mAdapter.getData().get(position).getCommentId());
        HttpUtils.post(Config.MOMENTS_CANCEL_LAUD, params, new HttpCallBack(mActivity) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                Tool.showTextToast(activity, message);
                MomentsAttentionList moments=mAdapter.getData().get(position);
                moments.setMyLaud("0");
                moments.setLaudNumber((Integer.parseInt(moments.getLaudNumber()) - 1) + "");
                mAdapter.notifyItemChanged(position);

            }

            @Override
            public void onError(String code, String message) {
                Tool.showTextToast(activity, message);
            }
        });
    }

    //关注
    private void AddConcern(final  int position){
        HttpParams params = new HttpParams();
        params.put("commentId",  mAdapter.getData().get(position).getCommentId());
        HttpUtils.post(Config.MOMENTS_COMMUNITY_ADDCONCERN, params, new HttpCallBack(mActivity) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                Tool.showTextToast(activity, message);
                MomentsAttentionList moments=mAdapter.getData().get(position);
                moments.setMyConcern("1");
                mAdapter.notifyItemChanged(position);
                onRefresh();
            }

            @Override
            public void onError(String code, String message) {
                Tool.showTextToast(activity, message);
            }
        });
    }
    //取消关注
    private void CancelConcern(final  int position) {

        HttpParams params = new HttpParams();
        params.put("commentId",  mAdapter.getData().get(position).getCommentId());
        HttpUtils.post(Config.MOMENTS_COMMUNITY_CANCELCONCERN, params, new HttpCallBack(mActivity) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                Tool.showTextToast(activity, message);
                MomentsAttentionList moments=mAdapter.getData().get(position);
                moments.setMyConcern("0");
                mAdapter.notifyItemChanged(position);
                onRefresh();
            }

            @Override
            public void onError(String code, String message) {
                Tool.showTextToast(activity, message);
            }
        });


    }

    private void getAttentionData(int pageNo, final boolean isPull){
        HttpParams params = new HttpParams();
        params.put("pageSize", "10");
        params.put("pageNo", pageNo + "");
        HttpUtils.post(Config.MOMENTS_ATTENTION, params, new HttpCallBack(mActivity) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                if (isPull){
                    mAdapter.clear();
                }
                 bean=AbJsonUtil.fromJson(result.toString(),MomentsAttentionBean.class);
                 mList=bean.getCommentList();
                if (mList==null||mList.size()==0){
                    showNoData("暂无数据");
                }else{
                    removeStatus();
                    mAdapter.addAll(mList);
                }
            }

            @Override
            public void onError(String code, String message) {

                showNoNewWork(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getAttentionData(1,true);
                    }
                });

                Tool.showTextToast(mActivity, message);
            }

            @Override
            public void onAfter(boolean isFromCache, JSONObject jsonObject, Call call, Response response, Exception e) {
                super.onAfter(isFromCache, jsonObject, call, response, e);
                if (mRefresh.isRefreshing()){
                    mRefresh.setRefreshing(false);
                }else{
                    mRefresh.setLoadingMore(false);
                }
            }
        });
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


    /**
     * 加载更多
     */
    @Override
    public void onLoadMore() {
        if (bean.pageNo<bean.totalPage){
            int  pageNo=bean.pageNo+1;
            getAttentionData(pageNo,false);
        }else{
            AbToastUtil.showToast(activity,"已无更多内容");
            mRefresh.setLoadingMore(false);
        }

    }

    /**
     * 下拉刷新
     */
    @Override
    public void onRefresh() {
        getAttentionData(1,true);
    }

    @Override
    public void onResume() {
        super.onResume();
        onRefresh();
    }
}
